package com.y.ari.controller;


import cn.hutool.core.util.StrUtil;
import com.y.ari.common.Constants;
import com.y.ari.common.RestResponse;
import com.y.ari.dto.EmpFormDTO;
import com.y.ari.dto.EmployeeDTO;
import com.y.ari.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 员工信息 前端控制器
 * </p>
 *
 * @author itcast
 */
@Slf4j
@RestController
@RequestMapping("/emp")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 登录
     */
    @PostMapping("/login")
    public RestResponse login(@RequestBody EmpFormDTO empFormDTO) {
        return employeeService.login(empFormDTO);
    }

    /**
     * 退出登录
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public RestResponse logOut(HttpServletRequest request) {
        // 1.获取请求头中的token
        String token = request.getHeader("authorization").substring(8);
        if (StrUtil.isBlank(token)) {
            return RestResponse.success("退出成功");
        }
        // 2.基于TOKEN获取redis中的用户
        String key = Constants.LOGIN_USER_KEY + token;
        Boolean aBoolean = redisTemplate.delete(key);
        if (aBoolean) {
            return RestResponse.success("退出成功");
        }
        return RestResponse.validfail(Constants.net_err);
    }

    /**
     * 查询员工列表
     *
     * @return
     */
    @PostMapping("/sel")
    public RestResponse selEmp() {
        return employeeService.selEmp();
    }

    /**
     * 更新员工列表
     *
     * @return
     */
    @PostMapping("/save")
    public RestResponse save(@RequestBody EmployeeDTO employeeDTO) {
        return employeeService.save(employeeDTO);
    }

    /**
     * del emp
     *
     * @return
     */
    @DeleteMapping("/del/{id}")
    public RestResponse delEmp(@PathVariable Long id) {
        return employeeService.delEmp(id);
    }
}
